#!/bin/bash

# ============================================
# 排查前端登录 Network Error
# ============================================

echo "=== 排查前端登录 Network Error ==="
echo ""

# 1. 检查 Nginx 代理配置
echo "1. 检查 Nginx 代理配置..."
grep "proxy_pass" /etc/nginx/conf.d/frontend.conf | grep -v "#"

# 2. 测试后端直接访问
echo ""
echo "2. 测试后端直接访问..."
echo "测试 /api/login/:"
curl -s -o /dev/null -w "HTTP Status: %{http_code}\n" -X POST http://127.0.0.1:8000/api/login/ -H "Content-Type: application/json" -d '{}' || echo "后端未响应"

# 3. 测试通过 Nginx 代理访问
echo ""
echo "3. 测试通过 Nginx 代理访问..."
echo "测试 /api/login/ (通过 Nginx):"
curl -s -o /dev/null -w "HTTP Status: %{http_code}\n" -X POST http://127.0.0.1/api/login/ -H "Content-Type: application/json" -d '{}' || echo "代理失败"

# 4. 检查 Nginx 错误日志
echo ""
echo "4. 最近的 Nginx 错误日志："
sudo tail -10 /var/log/nginx/frontend_error.log 2>/dev/null || echo "无错误日志"

# 5. 检查访问日志
echo ""
echo "5. 最近的访问日志："
sudo tail -5 /var/log/nginx/frontend_access.log 2>/dev/null || echo "无访问日志"

# 6. 检查前端构建配置
echo ""
echo "6. 检查前端构建配置..."
cd /mnt/lwy/django-vue3-admin/web 2>/dev/null || cd /root/OCR_CER_AUIDT_ADMIN/django-vue3-admin/web 2>/dev/null || cd web
if [ -f ".env.production" ]; then
    echo "当前 .env.production:"
    cat .env.production
else
    echo "⚠ .env.production 不存在"
fi

# 7. 检查前端构建后的文件
echo ""
echo "7. 检查前端构建文件..."
if [ -f "dist/index.html" ]; then
    echo "✓ dist/index.html 存在"
    echo "查找 API URL 配置："
    grep -r "VITE_API_URL\|localhost\|127.0.0.1\|10.170.129.4" dist/ 2>/dev/null | head -3 || echo "未找到 API URL 配置"
else
    echo "⚠ dist/index.html 不存在"
fi

# 8. 检查后端服务状态
echo ""
echo "8. 检查后端服务状态..."
ps aux | grep "manage.py runserver" | grep -v grep || echo "⚠ 后端服务未运行"

# 9. 测试 CORS
echo ""
echo "9. 测试 CORS 配置..."
curl -v -X OPTIONS http://127.0.0.1:8000/api/login/ -H "Origin: http://10.170.129.4" -H "Access-Control-Request-Method: POST" 2>&1 | grep -i "access-control" || echo "未找到 CORS 头"

echo ""
echo "=== 排查完成 ==="
echo ""
echo "可能的问题："
echo "1. 前端构建时的 VITE_API_URL 配置不正确"
echo "2. Nginx 代理配置有问题"
echo "3. 后端 CORS 配置有问题"
echo "4. 后端服务未运行或端口不对"

